/*
 * @Author: your name
 * @Date: 2021-10-21 22:36:25
 * @LastEditTime: 2021-10-25 22:41:16
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \webrtc_easy_signal\proto.go
 */
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"sync"
	"time"
)

type Request struct {
	Type int                    `json:"type"`
	Data map[string]interface{} `json:"data"`
}

const (
	REQ_LOGIN = 1000
)

type Peer struct {
	Name string        // 用户名
	Ws   *WsConnection // websocket连接
	Room *Room         // 当前处在哪个房间
}

type Room struct {
	Name  string           // 房间名称
	ws    *WsConnection    // websocket连接
	Peers map[string]*Peer // 在房间里的节点
}

var gmapRoom sync.Map
var gmapUser sync.Map

func get_room_online(name string) *Room {
	room, ok := gmapRoom.Load(name)
	if ok {
		return room.(*Room)
	}
	return nil
}

func get_peers_online(name string) *Peer {
	peer, ok := gmapUser.Load(name)
	if ok {
		return peer.(*Peer)
	}
	return nil
}

func get_interface_string(v interface{}) string {
	ret, ok := v.(string)
	if ok {
		return ret
	}
	return ""
}

func ProtoUnconnect(ws *WsConnection) {
	if nil == ws {
		return
	}
	// foundname := ""
	// gmapUser.Range(func(key, value interface{}) bool {
	// 	if value.(*Peer).Ws == ws {
	// 		foundname = value.(*Peer).Name
	// 		if value.(*Peer).Room != nil {
	// 			delete(value.(*Peer).Room.Peers, foundname)

	// 			peers_in_room := map[string]interface{}{}
	// 			for _, v := range value.(*Peer).Room.Peers {
	// 				peers_in_room[v.Name] = true
	// 			}
	// 			for _, v := range value.(*Peer).Room.Peers {
	// 				v.Ws.SendPayload(RESP_LISTROOM, peers_in_room)
	// 			}
	// 		}
	// 	}
	// 	return true
	// })
	// gmapUser.Delete(foundname)

}

func ProtoCallBack(ws *WsConnection, dat []byte) {
	if nil == ws {
		return
	}
	var payload Request
	e := json.Unmarshal(dat, &payload)
	if nil != e {
		log.Print(e.Error())
	}
	switch payload.Type {
	case 1001:
		motor := Motor{}

		config_name, ok := payload.Data["config_name"]
		if ok {
			motor.ConfigName = config_name.(string)
		}
		sn, ok := payload.Data["sn"]
		if ok {
			motor.Sn = sn.(string)
		} else {
			return
		}
		if sn != "" {
			models := []Motor{}
			// 查找序列号是否实现
			gOrm.Model(&Motor{}).
				Where(fmt.Sprintf("sn = '%s' ", sn)).Find(&models)

			log.Print(len(models))
			if len(models) == 1 {
				models[0].ConfigTime = time.Now()
				err := gOrm.Model(&Motor{}).
					Where(fmt.Sprintf("sn = '%s' ", sn)).Update(&models[0]).Error
				if err != nil {
					log.Print(err.Error())
				}
			} else if len(models) == 0 {
				motor.ConfigTime = time.Now()
				err := gOrm.Model(&Motor{}).
					Where(fmt.Sprintf("sn = '%s' ", sn)).Create(&motor).Error
				if nil != err {
					log.Print(err.Error())
				}
			}
		}

		break
	}
}
